package com.itrip.log.util;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

/**
 * Function:模板管理类
 *
 * @date:2016年7月20日/下午5:19:37
 * @Author:jeff@aoliday.cao
 * @version:1.0
 */
public class VelocityUtil {

	private static final VelocityUtil INSC = new VelocityUtil();
	private VelocityEngine ve = new VelocityEngine();

	private VelocityUtil() {
		Properties prop = new Properties();
		// prop.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "./");
		prop.setProperty(Velocity.ENCODING_DEFAULT, "utf-8");
		prop.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
		prop.setProperty(Velocity.INPUT_ENCODING, "utf-8");
		ve.init(prop);
	}

	public static VelocityUtil getIns() {
		return INSC;
	}

	public String getTemplate(String filePath, Map<String, Object> map, Writer writer) {
		VelocityContext context = new VelocityContext();
		for (Entry<String, Object> en : map.entrySet()) {
			context.put(en.getKey(), en.getValue());
		}
		Template t = ve.getTemplate(filePath);
		t.merge(context, writer);
		return writer.toString();
	}

	public String getTemplate(String filePath, Map<String, Object> map) {
		return getTemplate(filePath, map, new StringWriter());
	}
}
